package com.gls.security.core.configurer.builder;

import com.gls.security.core.configurer.adapter.RequestMatcherConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lizhiyong
 */
@Component
public class DefaultRequestMatcherConfigurerBuilder implements RequestMatcherConfigurerBuilder {

    @Autowired(required = false)
    private List<RequestMatcherConfigurerAdapter> requestMatcherConfigurerAdapters;

    @Override
    public void configure(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry) {
        boolean existAnyRequestConfig = false;
        String existAnyRequestConfigName = null;

        if (requestMatcherConfigurerAdapters != null) {
            for (RequestMatcherConfigurerAdapter configurer : requestMatcherConfigurerAdapters) {
                boolean currentIsAnyRequestConfig = configurer.configure(expressionInterceptUrlRegistry);
                if (existAnyRequestConfig && currentIsAnyRequestConfig) {
                    throw new RuntimeException("重复的anyRequest配置:" + existAnyRequestConfigName + ","
                            + configurer.getClass().getSimpleName());
                } else if (currentIsAnyRequestConfig) {
                    existAnyRequestConfig = true;
                    existAnyRequestConfigName = configurer.getClass().getSimpleName();
                }
            }
        }

        if (!existAnyRequestConfig) {
            expressionInterceptUrlRegistry.anyRequest().authenticated();
        }
    }
}
